/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "memorymap.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "wifi.h"
#include "bsp_sht20.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
int fputc(int ch, FILE * p)
{
	while(!(USART1->ISR & 1<<7));//等待TDR为空，即TXE置1，跳出while，然后往TDR中放数据
	USART1->TDR=ch;
	return ch;
}
typedef struct
{
  const char *cmd_name;  // 命令字符串
  void (*handler)(void); // 对应的处理函数
} CommandEntry;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
// 置位（第 position 位设为1）
#define SET_myBIT(data, position)    ((data) |= (1 << (position)))
// 清零（第 position 位设为0）
#define CLEAR_myBIT(data, position)  ((data) &= ~(1 << (position)))
// 判断（第 position 位是否为1）
#define CHECK_myBIT(data, position)  ((data) & (1 << (position)))
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint8_t USART5_RxBuff[1024]={0};
volatile uint8_t USART5_RxCounter=0;

/*
* 变量名： list
*	位： LED1 -> 1; LED3 -> 2; Fan -> 3; Buzzer -> 4; Vibrator -> 5
* 值： 1 -> 开; 0 -> 关
*/
uint32_t list = 0; //状态表
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void LED1_ON() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_4, GPIO_PIN_SET); SET_myBIT(list,1);}  //LED
void LED1_OFF() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_4, GPIO_PIN_RESET); CLEAR_myBIT(list,1);}
void LED3_ON() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET); SET_myBIT(list,2);}
void LED3_OFF() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET);CLEAR_myBIT(list,2); }
void Fan_ON() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_6, GPIO_PIN_SET); SET_myBIT(list,3);}  //风扇
void Fan_OFF() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_6, GPIO_PIN_RESET); CLEAR_myBIT(list,3);}
void Buzzer_ON() { HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, 1);SET_myBIT(list,4); }  //蜂鸣器
void Buzzer_OFF() { HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET); CLEAR_myBIT(list,4);}
void Vibrator_ON() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, GPIO_PIN_SET);SET_myBIT(list,5); }  //马达
void Vibrator_OFF() { HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, GPIO_PIN_RESET);CLEAR_myBIT(list,5);}
void Fire() { if (HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_3) == GPIO_PIN_SET) { SET_myBIT(list,6); Buzzer_ON(); } else {CLEAR_myBIT(list,6); Buzzer_OFF(); } }
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

CommandEntry commands[] = {
	{"led:1", LED1_ON},  //led
	{"led:0", LED1_OFF},
	{"led3:1", LED3_ON},  //led3
	{"led3:0", LED3_OFF},
    {"fan:1", Fan_ON},//风扇
    {"fan:0", Fan_OFF},
    {"buzzer:1", Buzzer_ON},//蜂鸣器
    {"buzzer:0", Buzzer_OFF},
    {"vibrator:1", Vibrator_ON},//马达
    {"vibrator:0", Vibrator_OFF},
		{"fire",Fire}
};
	
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	if(huart == &huart5)
	{
		USART5_RxCounter=1;//此变量置1，则代表wifi发过来了数据
		if(connect_flag == 1)
		{
			u1_USART("server:%s\n",USART5_RxBuff);
			for (int i = 0; i < sizeof(commands)/sizeof(CommandEntry); i++)
			{
				if (strstr((char *)USART5_RxBuff,commands[i].cmd_name))
				{
					commands[i].handler();
				}
			}
			memset(USART5_RxBuff,0,1024);
		}

		HAL_UARTEx_ReceiveToIdle_IT(&huart5,USART5_RxBuff,1024);
	}
}


void SendValue()
{
	BSP_SHT20_GetData();
	char buffer[128] = {};
	sprintf(buffer,"state:%d;Tem:%f;Hum:%f\n",list,getTH_Val.Tem,getTH_Val.Hum);
	ESP8266_USART("%s",buffer);
	u1_USART("%s",buffer);
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_UART5_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
	HAL_UARTEx_ReceiveToIdle_IT(&huart5,USART5_RxBuff,1024);
	WIFI_Connect();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		Fire();
		SendValue();
		HAL_Delay(1000);
    /* USER CODE END WHILE */
		
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE4) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_4;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_PCLK3;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
